/**
 * @description 监听快捷键
 * @author 大肘子
 */

import { useKeyPress } from "ahooks";
import { useDispatch } from "react-redux";
import { deleteComponent, copyComponentFun, pasteComponent, selectPrevComponent, selectNextComponent } from "../store/componentReducer";
//映入撤销重做
import { ActionCreators } from "redux-undo";
function isActiveElement() {
  const activeElement = document.activeElement;
  console.log(activeElement?.matches('div[role="button"]'));
  // activeElement == document.body
  if (activeElement?.matches('div[role="button"]')) {
    return true;
  } else {
    return false;
  }
}

function useBindKeyPress() {
  const dispatch = useDispatch();

  //监听删除快捷键
  useKeyPress(["backspace", "delete"], () => {
    if (isActiveElement()) {
      dispatch(deleteComponent());
    }
  });
  //复制
  useKeyPress(["ctrl.c"], () => {
    if (isActiveElement()) {
      dispatch(copyComponentFun());
    }
  });
  //粘贴
  useKeyPress(["ctrl.v"], () => {
    if (isActiveElement()) {
      dispatch(pasteComponent());
    }
  });
  //上移
  useKeyPress(["uparrow"], () => {
    if (isActiveElement()) {
      dispatch(selectPrevComponent());
    }
  });
  //下移
  useKeyPress(["downarrow"], () => {
    if (isActiveElement()) {
      dispatch(selectNextComponent());
    }
  });
  //撤销
  useKeyPress(
    ["ctrl.z"],
    () => {
      if (isActiveElement()) {
        dispatch(ActionCreators.undo());
      }
    },
    {
      exactMatch: true,
    },
  );
  //重做
  useKeyPress(["ctrl.shift.z"], () => {
    if (isActiveElement()) {
      dispatch(ActionCreators.redo());
    }
  });
}

export default useBindKeyPress;
